package com.ht.shortlink.project.mq.idempotent;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.ht.shortlink.project.common.constant.RedisCacheConstant.SHORT_LINK_MESSAGE_QUEUE_PROCESSED_KEY;

/**
 *  消息队列幂等处理器
 */
@Component
@RequiredArgsConstructor
public class MessageQueueIdempotentHandler {
    private final StringRedisTemplate stringRedisTemplate;

    /**
     *  判断消息是否被处理过
     * @param messageId 消息ID
     */
    public boolean isMessageQueueProcessed(String messageId){
        String key = String.format(SHORT_LINK_MESSAGE_QUEUE_PROCESSED_KEY, messageId);
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "0", 2L, TimeUnit.MINUTES);
        return Boolean.FALSE.equals(flag);
    }

    /**
     *  删除消息处理标识
     * @param messageId 消息ID
     */
    public void deleteMessageQueueProcessedKey(String messageId){
        stringRedisTemplate.delete(String.format(SHORT_LINK_MESSAGE_QUEUE_PROCESSED_KEY, messageId));
    }

    /**
     *  判断消息是否处理完成
     * @param messageId 消息ID
     * @return
     */
    public boolean isMessageQueueAccomplished(String messageId){
        String key = String.format(SHORT_LINK_MESSAGE_QUEUE_PROCESSED_KEY, messageId);
        if(ObjectUtil.equals("1", stringRedisTemplate.opsForValue().get(key)))
            return true;
        else
            return false;
    }

    /**
     *  标识消息完成
     * @param messageId 消息ID
     */
    public void setMessageQueueAccomplished(String messageId){
        String key = String.format(SHORT_LINK_MESSAGE_QUEUE_PROCESSED_KEY, messageId);
        stringRedisTemplate.opsForValue().set(key, "1");
    }
}